﻿// <copyright file="KingsCache.cs" company="Ecole Normale Supérieure">
// Released under GPLv2
// </copyright>
// <summary>Contains the KingsCache.</summary>

namespace Sqwarea.GameLogic.View
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Sqwarea.Persistence;

    /// <summary>
    /// A cache for kings used by SquareView.
    /// SquareView needs in fact to get information about kings of squares and request often the same kingId.
    /// </summary>
    public class KingsCache : IKingsCache
    {
        /// <summary>
        /// Game provider
        /// </summary>
        private readonly IGameProvider _gameProvider;

        /// <summary>
        /// Contents of the cache for kings
        /// </summary>
        private readonly Dictionary<long, King> _kings;

        /// <summary>
        /// Initializes a new instance of the KingsCache class.
        /// Notice you should (re)create often new KingsCache for not having outdated data.
        /// </summary>
        /// <param name="gameProvider">The Game Provider.</param>
        public KingsCache(IGameProvider gameProvider)
        {
            if (null == gameProvider)
            {
                throw new ArgumentNullException("gameProvider", "KingsCache");
            }

            this._gameProvider = gameProvider;
            this._kings = new Dictionary<long, King>();
        }

        /// <summary>
        /// Get a king using cache.
        /// Notice you can get a neutral king if id==NeutralKingId (different from GetKingById of Persistence)
        /// </summary>
        /// <param name="id">The id of the king</param>
        /// <returns>The king (UpdateAcademyTroops and UpdateNeutralId are NOT called on the king)</returns>
        public King GetKingById(long id)
        {
            if (id == King.NeutralKingId)
            {
                return new King(King.NeutralKingId, null, null);
            }

            if (_kings.ContainsKey(id))
            {
                return _kings[id];
            }
            else
            {
                var king = _gameProvider.GetKingById(id);
                _kings.Add(id, king);
                return king;
            }
        }
    }
}
